package com.pagoda.nerp.trade.common.extend;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局拦截器，主要用户对请求报文进行一个展示
 * Created by Jungle on 2016/12/15.
 */
public class RequestInterceptorForAdmin implements HandlerInterceptor{

    private static final Logger logger = LoggerFactory.getLogger(RequestInterceptorForAdmin.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        try {
            this.parseRequestParam2JSONObj(httpServletRequest);
        }catch (Exception e){
            logger.error("解析请求报文异常!",e);
        }
        try {
            // 静态资源不处理，结合springmvc仅接受application/json格式进行处理
            String contentType = httpServletRequest.getContentType();
            if(null == contentType || contentType.indexOf("application/json") == -1){
                logger.info("Intercepero 当前请求非application/json头信息，不进行拦截");
                return true;
            }
            // 处理ajax异步请求 ，如果头信息携带了X-Requested-With 则为异步ajax请求
            String type = httpServletRequest.getHeader("X-Requested-With");
            if(type != null && "XMLHttpRequest".equalsIgnoreCase(type)){
                // 登录请求不进行拦截 ， 直接方行
                String url = httpServletRequest.getRequestURI();
                if(null != url && url.indexOf("login") >= 0){
                    return true;
                }
                // 非登录请求进行session的校验，如果失效了则设置头信息为sessionstatus=timeout
                HttpSession session = httpServletRequest.getSession();
                String userCode = (String)session.getAttribute("userCode");
                if(userCode != null){
                    return true;
                }
                logger.debug("Interceptor 当前会话已经失效，设置头信息[sessionstatus]=>[timeout]，进行重定向处理");
                httpServletResponse.setHeader("sessionstatus", "timeout");
                return false;
            }
        }catch (Exception e){
            logger.error("Intercepter 拦截器执行失败，登录过滤失败!",e);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


    /**
     * 获取URL上面的请求参数
     * @param request
     * @return
     */
    protected String parseRequestParam2JSONObj(HttpServletRequest request) throws Exception {
        try {
            Enumeration e = request.getParameterNames();
            Map<String, String> map = new HashMap<String, String>();
            while (e.hasMoreElements()) {
                String key = e.nextElement().toString();
                String value = request.getParameter(key);
                map.put(key, value);
            }
            String jsonStr = JSON.toJSONString(map, true);
            logger.info("拦截器：请求的body携带URL参数为：{}",jsonStr);
            return jsonStr;
        }catch (Exception e){
            logger.error("拦截器：请求的body不是URL带参格式！", e);
        }
        return null;
    }

}
